import tkinter
from PIL import Image, ImageTk
import tkmacosx
from tkinter.messagebox import *
import webbrowser
import gui_list
import requests


def resize(w_box, h_box, pil_image):
    # 参数是：要适应的窗口宽、高、Image.open后的图片
    # 处理自适应大小
    w, h = pil_image.size  # 获取图像的原始大小
    f1 = 1.0 * w_box / w
    f2 = 1.0 * h_box / h
    factor = min([f1, f2])
    width = int(w * factor)
    height = int(h * factor)
    return pil_image.resize((width, height), Image.ANTIALIAS)


def check_login():
    # button按钮调用
    button_text.set("正在登陆中")
    ses = requests.Session()
    dic = {'username': username_str.get(), "passwd":password_str.get()}
    url = "http://127.0.0.1:4000/check"
    try:
        ses.post(url, dic)
        print(requests.post(url, dic).text)
    except requests.exceptions.ConnectionError:
        showinfo("showinfo", "连接超时")
        button_text.set("登陆")
        return 0
    res = requests.post(url, dic).text
    if res == "登陆成功":
        log.destroy()
        gui_list.create_gui_list(username_str.get())
        return 0
    else:
        showinfo("showinfo", res)
        button_text.set("登陆")

if __name__ == '__main__':
    # 图形化界面代码
    import sys
    import os
    curPath = os.path.abspath(os.path.dirname(__file__))
    rootPath = os.path.split(curPath)[0]
    sys.path.append(rootPath)
    print(rootPath)
    log = tkinter.Tk()
    log.title("we talk")
    log.geometry('300x420')
    # can = tkinter.Canvas(log, height=200, width=200)
    img1 = Image.open(r'img/logo.png')
    img1 = resize(72, 72, img1)
    img2 = ImageTk.PhotoImage(img1)
    img_label = tkinter.Label(log, image=img2)
    img_label.pack()
    username_str = tkinter.StringVar()
    username = tkinter.Entry(bg="white", fg="black", textvariable=username_str)
    username_str.set("15133854715")
    password_str = tkinter.StringVar()
    password = tkinter.Entry(bg="white", fg="black", textvariable=password_str, show='*')
    password_str.set("yujihao258")
    username.pack()
    password.pack()
    # window可能会用到
    # login = tkinter.Button(log, text="登陆",bg="green",fg="black")
    button_text = tkinter.StringVar()
    button_text.set("登陆")
    login = tkmacosx.Button(log, textvariable=button_text, bg="#339933",fg="white",width=180,height=40,command=check_login)
    # 新增
    forget = tkinter.Label(log, text="首页", justify='left',fg="black")
    getnew = tkinter.Label(log, text="注册账号", justify='right',fg ='black')
    # 目前打不开网页，Windows运行正常，Mac打不开
    forget.bind("<Button-1>", lambda x: webbrowser.open_new_tab("http://127.0.0.1:4000"))
    getnew.bind("<Button-1>", lambda x: webbrowser.open_new_tab("http://127.0.0.1:4000/reg"))
    login.pack()
    forget.pack()
    getnew.pack()
    log.mainloop()
